<template>
	<view>
		<uni-file-picker v-model="imageValue" fileMediatype="image" mode="grid" @select="select" @delete="deleteFile" />
	</view>
</template>

<script>
	import constant from "@/utils/constant.js"

	export default {
		data() {
			return {
				fileHost: constant.fileHost,
				imageValue: [],
				appendFiles: [],
				originFiles: [],
				uuid: "",
			}
		},
		onLoad(option) {
			this.uuid = option.uuid;
			if (option.imageUrls) {
				const imageUrls = JSON.parse(decodeURIComponent(option.imageUrls));
				let serverData = []
				if (imageUrls.length > 0) {
					serverData = imageUrls.map(item => {
						let url = item;
						const name = item.split("/");
						const fileName = name[name.length - 1];
						if (url.indexOf("/storage") < 0) {
							url = this.fileHost + url;
						}
						this.originFiles.push({
							url: item,
							name: fileName
						})
						return {
							url: url,
							name: fileName,
							extname: fileName.split(".")[1]
						};
					});
				}
				this.imageValue = [
					...serverData,
					...this.getStoreFile
				];
			} else {
				this.imageValue = this.getStoreFile;
				this.appendFiles = this.getStoreFile;
			}
		},
		computed: {
			getStoreFile() {
				return this.$store.state.file[`pic_files_${this.uuid}`]?.appendFiles || []
			}
		},
		methods: {
			// 获取上传状态
			select(e) {
				e.tempFiles.forEach(item => {
					this.imageValue.push({
						name: item.name,
						extname: item.extname,
						url: item.url,
					});
					this.appendFiles.push({
						name: item.name,
						extname: item.extname,
						url: item.url,
					})
				});
				this.$store.commit('SAVE_PIC', {
					uuid: this.uuid,
					files: {
						originFiles: this.originFiles,
						appendFiles: this.appendFiles
					}
				})
			},
			deleteFile(e) {
				const delFile = e.tempFile.name
				this.imageValue = this.imageValue.filter(item => {
					return item.name !== delFile
				})
				this.originFiles = this.originFiles.filter(item => {
					return item.name !== delFile
				})
				this.appendFiles = this.appendFiles.filter(item => {
					return item.name !== delFile
				})
				this.$store.commit('SAVE_PIC', {
					uuid: this.uuid,
					files: {
						originFiles: this.originFiles,
						appendFiles: this.appendFiles
					}
				})
			}
		}
	}
</script>

<style>
	page {
		background-color: #ffffff;
	}
</style>

<style lang="scss" scoped>
	.example-body {
		padding: 10px;
		padding-top: 0;
	}
</style>